package cn.edu.stu.syllabus.repository.banner.local;

import android.content.Context;
import android.content.SharedPreferences;

import cn.edu.stu.syllabus.application.SyllabusApplication;
import cn.edu.stu.syllabus.repository.banner.BannerDataSource;
import cn.edu.stu.syllabus.utils.GsonUtils;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by daidaijie on 2017/3/13.
 */

public class BannerLocalDataSource implements BannerDataSource {

    private static final String TAG = "BannerLocalDataSource";

    private static final String EXTRA_BANNER_INFO = "bannerInfo";

    @Override
    public Observable<BannerInfoEntry> getBannerInfos() {
        return Observable.create(new Observable.OnSubscribe<BannerInfoEntry>() {
            @Override
            public void call(Subscriber<? super BannerInfoEntry> subscriber) {
                SharedPreferences sharedPreferences
                        = SyllabusApplication.getContext().getSharedPreferences(TAG, Context.MODE_PRIVATE);
                String bannerInfoString = sharedPreferences.getString(EXTRA_BANNER_INFO, "");
                BannerInfoEntry bannerInfoEntry = GsonUtils.getInstance().fromJson(bannerInfoString, BannerInfoEntry.class);
                if (bannerInfoEntry != null) {
                    subscriber.onNext(bannerInfoEntry);
                }
                subscriber.onCompleted();
            }
        });
    }

    @Override
    public void saveBannerInfo(BannerInfoEntry bannerInfoEntry) {
        SharedPreferences sharedPreferences
                = SyllabusApplication.getContext().getSharedPreferences(TAG, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String bannerInfoString = GsonUtils.getInstance().toJson(bannerInfoEntry);
        editor.putString(EXTRA_BANNER_INFO, bannerInfoString);
        editor.apply();
    }

}
